package ee.serge.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.GwtEvent;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.event.shared.SimpleEventBus;
import com.google.gwt.user.client.Window;

public class PushState implements HasValueChangeHandlers<String> {

   private static final PushState PUSH_STATE = new PushState();
   
   public static PushState get() {
      return PUSH_STATE;
   }

   private EventBus bus = new SimpleEventBus();
   
   public PushState() {
      if (!init()) {
         Window.alert("error");
         GWT.log("ERROR");
      }
            
   }
   
   private native boolean init() /*-{
      $entry(this.@ee.serge.client.PushState::syso(Ljava/lang/String;)("init"));
      $wnd.onpopstate = $entry(function() {
         $entry(this.@ee.serge.client.PushState::syso(Ljava/lang/String;)("popstate"));
         $wnd.alert("popstate");
      });
      $wnd.onhashchange = $entry(function() {
         $entry(this.@ee.serge.client.PushState::syso(Ljava/lang/String;)("hash"));
         $wnd.alert("hash");
      });
      return true;
   }-*/;
   
   public native void pushState(String url) /*-{
      //$wnd.onpopstate = $entry(this.@ee.serge.client.PushState::syso(Ljava/lang/String;)("helo"));
      $wnd.history.pushState({}, "", url);
      this.@ee.serge.client.PushState::syso(Ljava/lang/String;)(url);
      //this.@ee.serge.client.PushState::onPushState(Ljava/lang/String;)(url);
   }-*/;
   
   public void onPushState(String url) {
      ValueChangeEvent.fire(this, url);
   }
   
   private void syso(String str) {
      GWT.log(str);
      System.out.println(str);
   }

   @Override
   public HandlerRegistration addValueChangeHandler(ValueChangeHandler<String> handler) {
      return bus.addHandler(ValueChangeEvent.getType(), handler);
   }

   @Override
   public void fireEvent(GwtEvent<?> event) {
      bus.fireEvent(event);
   }
   
}
